<script setup lang="ts">
import { useRouter } from 'vue-router';
import { ref, computed } from 'vue';
import type { Ref, ComputedRef } from 'vue'
import { loginFn } from '@/api/user';

// 导入全局状态管理
import { useCounterStore } from '@/stores/counter';
import { useUserInfoStore } from '@/stores/user';
import { showToast } from 'vant';

const countStore = useCounterStore()
const userInfoStore = useUserInfoStore()

// 以 use 开头的函数是 hooks 只能在外层使用
const router = useRouter()
const loginname: Ref<string> = ref('')
const password: Ref<string> = ref('')

const isClick: ComputedRef<boolean> = computed(() => {

    if (!password.value) return false

    return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(loginname.value)
})

function backClick() {

    // this.$router.back()
    router.back()
}

// 登录的提交事件
function onSubmit() {
    loginFn({
        loginname: loginname.value,
        password: password.value
    }).then(res => {
        // console.log(res);
        if (res.data.code == '200') {
            // 登录成功
            // 1. 将用户数据保存在全局状态管理中
            userInfoStore.changeUserInfo(res.data.data)

            // 2. 跳转到首页
            router.replace('/')
        } else {
            showToast(res.data.message)
        }
    })
}

</script>
<template>
    <main class="box">
        <header class="header">
            <van-icon @click="backClick" class="back" name="arrow-left" />
            <span>头部-登录</span>
        </header>

        <div class="content">
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="loginname" name="手机号" label="手机号" placeholder="手机号"
                        :rules="[{ pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请正确填写手机号' }]" />
                    <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                        :rules="[{ required: true, message: '请填写密码' }]" />
                </van-cell-group>
                <div style="padding: 0 20px;">
                    <van-button :disabled="!isClick" style="margin: 26px 0 26px 0;" color="#f66" round block
                        native-type="submit">
                        登 录
                    </van-button>
                    <van-button @click="$router.push('/register')" round block type="primary">
                        注 册
                    </van-button>
                </div>
            </van-form>
            <hr>
            <div>
                <h1>{{ countStore.count }} -- {{ countStore.doubleCount }} </h1>
                <van-button @click="countStore.increment()">点击增加</van-button>
            </div>
        </div>
    </main>
</template>
<style scoped lang="scss">
.back {
    float: left;
    font-size: .2rem;
    line-height: .44rem;
    padding-left: 10px;
}

.content {
    padding-top: 50px;
}
</style>